import React from 'react';
import { LockOutlined, UserOutlined } from '@ant-design/icons';
import { Button, Form, Input } from 'antd';
import API from '@/api';
import { setToken } from '@/utils/token';
import { useNavigate } from 'react-router-dom';
import { useAppDispatch } from '@/hooks/redux';
import { setUserInfo } from '@/redux/modules/userInfoReducer';

const initialValues = { mobile: '13888888888', code: '246810' };
const formRules = {
  userName: [{ required: true, message: '请输入用户名!' }],
  password: [
    { required: true, message: '请输入密码!' },
    { min: 6, max: 20, message: '长度在 6 到 20 个字符' }
  ]
}

const Login: React.FC = () => {
  const dispatch = useAppDispatch();
  const navigate = useNavigate();
  const [btnLoading, setBtnLoading] = React.useState(false);
  const onFinish = async (values: any) => {
    try {
      setBtnLoading(true);
      const tokenRes = await API.user.getToken({ mobile: values.mobile, code: values.code });
      setToken(tokenRes.data.token);
      const userInfoRes = await API.user.getInfo();
      dispatch(setUserInfo({ ...userInfoRes.data, ...tokenRes.data }));
      navigate('/');
    } catch (_) {
    } finally {
      setBtnLoading(false);
    }
  };

  return (
    <div className='login-container'>
      <div className="login-form">
        <h3 className='login-form-title'>登 录</h3>
        <Form name="normal_login" initialValues={ initialValues } onFinish={ onFinish }>
          <Form.Item name="mobile" hasFeedback rules={ formRules.userName }>
            <Input prefix={<UserOutlined />} placeholder="用户名" />
          </Form.Item>
          <Form.Item name="code" hasFeedback rules={ formRules.password }>
            <Input prefix={<LockOutlined />} type="password" placeholder="密码" />
          </Form.Item>
          <Form.Item>
            <Button type="primary" htmlType="submit" loading={ btnLoading } className="login-form-button">登录</Button>
          </Form.Item>
        </Form>
      </div>
    </div>
  )
};

export default Login;